<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>重新排列单词间的空格</title>
</head>
<body>
  <script>
    function fn(text) {
      const words = text.trim().split(/\s+/);
      let cnt = 0;
      for (const c of text) {
        if (c === ' ') {
          cnt++;
        }
      }
      if (words.length === 1) {
        return words[0] + ' '.repeat(cnt);
      }
      return words.join(' '.repeat(Math.floor(cnt / (words.length - 1)))) + ' '.repeat(cnt % (words.length - 1));
    }
    console.log(fn('  this   is  a sentence '))
  </script>
</body>
</html>